package com.googlecode.saucelabs;

import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Goal which touches a timestamp file.
 * 
 * @goal create-tunnel
 * 
 * @phase pre-integration-test
 */
public class CreateTunnelMojo extends AbstractSauceMojo {
	public void execute() throws MojoExecutionException, MojoFailureException {
		HttpClient httpClient = getHttpClient();
		try {
			// Part #1: Submits a tunnel creation request
			try {
				AbstractSauceCommand<String> sauceTunnelCreateCommand = new AbstractSauceCommand<String>(
						getRequest(HttpPost.class, "/rest/%s/tunnels", username)) {
					@Override
					public void onSetupConnection(HttpUriRequest httpUriRequest)
							throws Exception {
						JSONObject args = new JSONObject();

						args.put("DomainNames", new JSONArray(Arrays
								.asList(domains)));

						((HttpPost) httpUriRequest).setEntity(new StringEntity(
								args.toString()));
					}

					@Override
					public String onEntityResult(HttpResponse httpResult,
							String entityResult) throws Exception {
						JSONObject jsonResponse = new JSONObject(entityResult);

						return jsonResponse.getString("id");
					}
				};

				sauceTunnelCreateCommand.execute();
			} catch (Exception e) {
				throw new MojoExecutionException("Failure", e);
			}
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}
}
